﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Windows.Interop;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Media.Imaging;

namespace sunsetmp
{
    public class Core
    {
        #region var
        ThrearWorkClass ThreadWorker;
        PlayerWindow PlayerWindow;
        MediaWindow MediaWindow;
        MediaElement mediaElement;
        List<int> NextTrackMass;
        List<int> PrevTrackMass;
        int playingTrackPosition;
        int playingShufflePosition = -1;
        public bool shufflePlay = false;
        public bool repeatPlay = false;
        bool mediaIsPaused = false;
        public bool mediaIsStop = true;
        DataTable playingList;
        DataTable selectedLocalPL;
        DataTable selectedWebPL;
        DataTable groupTable;
        DataTable friendTable;
        Properties.Settings ps;
        System.Windows.Forms.Timer sliderTimer = new System.Windows.Forms.Timer();
        System.Windows.Forms.Timer stringTimer = new System.Windows.Forms.Timer();
        System.Windows.Forms.Timer timerTimer = new System.Windows.Forms.Timer();
        public bool sliderpressed = false;
        NotifyIcon MyNotifyIcon = new System.Windows.Forms.NotifyIcon();
        DateTime startTimer = DateTime.Now;
        public string access_token;
        string user_id;
        string group_id;
        string friend_id;
        System.Windows.Controls.MenuItem Aitem;
        System.Windows.Controls.MenuItem Titem;
        System.Windows.Controls.MenuItem ALitem;
        System.Windows.Controls.MenuItem Gitem;
        System.Windows.Controls.MenuItem WAitem;
        System.Windows.Controls.MenuItem WTitem;
        System.Windows.Controls.MenuItem WGitem;
        #endregion

        public Core (PlayerWindow playW)
        {
            PlayerWindow = playW;
            LoadNotiIcon();
            sliderTimer.Interval = 1000;
            sliderTimer.Tick += sliderTimer_Tick;
            stringTimer.Interval = 200;
            timerTimer.Interval = 1000;
            HotKey DropHotKey = new HotKey(Key.F7, KeyModifier.Ctrl, DropSettings,"");
        }

        private void DropSettings(HotKey hotKey)
        {
            ps.Reset();
            ps.Save();
            CloseAplication();
        }

        //----------------------------------------------------------------------------
        #region Горячие клавиши

        private void LoadHotKeys()
        {
            if (ps.HotKeys == "")
                return;
            Settings set = new Settings(this);
            Dictionary<string, string> dic = set.ConvertStringToDic(ps.HotKeys);
            foreach (string key in dic.Keys)
                if (dic[key] != "")
                    RegisterHotKey(key, dic[key]);
        }

        public void RegisterHotKey(string command, string combination)
        {
            combination = combination.Replace(" ", "");
            string[] split = combination.Split('+');
            KeyConverter conv = new KeyConverter();
            conv.ConvertFrom(split[split.Length-1]);
            KeyModifier modifers = new KeyModifier();
            Key key = Key.Home;
            for (int i = 0; i < split.Length; i++)
            {
                if (i == split.Length - 1)
                    key = (Key)conv.ConvertFrom(split[i]);
                else
                {
                    switch (split[i])
                    {
                        case "Ctrl":
                            modifers = modifers | KeyModifier.Ctrl;
                            break;
                        case "Alt":
                            modifers = modifers | KeyModifier.Alt;
                            break;
                        case "Shift":
                            modifers = modifers | KeyModifier.Shift;
                            break;
                        case "Win":
                            modifers = modifers | KeyModifier.Win;
                            break;
                    }
                }
            }
            HotKey hotKey = new HotKey(key, modifers,HotKeyFunc,command);
            
        }

        private void HotKeyFunc(HotKey hotKey)
        {
            string name = hotKey.Name;
            switch (name)
            {
                case "Воспроизвести/Приостановить":
                    PlayPause();
                    break;
                case "Следующий трек":
                    NextTrack();
                    break;
                case "Предыдущий трек":
                    PrevTrack();
                    break;
                case "Стоп":
                    Stop();
                    break;
                case "Проигрывать вперемешку":
                    shufflePlay = !shufflePlay;
                    PlayerWindow.RandomButton.IsChecked = !PlayerWindow.RandomButton.IsChecked;
                    break;
                case "Повторять текущий трек":
                    repeatPlay = !repeatPlay;
                    PlayerWindow.RepeatButton.IsChecked = !PlayerWindow.RepeatButton.IsChecked;
                    break;
                case "Скачать текущий трек":
                    if (playingList.Rows.Count != 0 && playingList.TableName == selectedWebPL.TableName)
                    {
                        var r = playingList.Rows[playingTrackPosition];
                        DialogWindow.DownloadWindow DW = new DialogWindow.DownloadWindow(r[2].ToString(), r[3] + ".mp3");
                    }
                    break;
                case "Показать/скрыть в трей":
                    ToTray_Func();
                    break;
                case "Поверх всех окон":
                    ChangeTopMost();
                    break;
                case "Громче":
                    if (mediaElement.Volume <= 0.95)
                        mediaElement.Volume += 0.05;
                    else
                        mediaElement.Volume = 1;
                    break;
                case "Тише":
                    if (mediaElement.Volume >= 0.05)
                        mediaElement.Volume -= 0.05;
                    else
                        mediaElement.Volume = 0;
                    break;
                case "Выключить звук":
                    mediaElement.IsMuted = !mediaElement.IsMuted;
                    break;
                case "Перемотать назад":
                    ChangeSliderValue(PlayerWindow.timelineSlider.Value - 5);
                    break;
                case "Перемотать вперед":
                    ChangeSliderValue(PlayerWindow.timelineSlider.Value + 5);
                    break;
                case "Добавить в мои аудиозаписи":
                    if (playingList.Rows.Count != 0 && playingList.TableName == selectedWebPL.TableName)
                    {
                        if (selectedWebPL.TableName.Split('#')[0] != "0")
                        {
                            var r = playingList.Rows[playingTrackPosition];
                            string doc = GetRequest("audio.add?aid=" + r[0] + "&oid=" + r[1]);
                            if (doc.IndexOf("error") > -1)
                                System.Windows.MessageBox.Show("Ошибка при добавлении трека");
                        }
                    }
                    break;
            }
        }

        #endregion
        //----------------------------------------------------------------------------
        #region Управление окнаим

        public void WindowSticking(Grid win)
        {
            
            int screenH = Screen.PrimaryScreen.WorkingArea.Height;
            int screenW = Screen.PrimaryScreen.WorkingArea.Width;
            double top = PlayerWindow.Top - PlayerWindow.PlayerHead.Height;
            if (top <= 0 || PlayerWindow.Left <= 0 || top + PlayerWindow.Height >= screenH || PlayerWindow.Left + PlayerWindow.Width >= screenW)
            {
                //главное окно
                    PlayerWindow.NavigateWindow();
                    if (PlayerWindow.Left + PlayerWindow.Width > screenW)
                        PlayerWindow.Left = screenW - PlayerWindow.Width ;
                    if (top + PlayerWindow.Height > screenH)
                        top = screenH - PlayerWindow.Height;
                    if (PlayerWindow.Left < 0)
                        PlayerWindow.Left = 0;
                    if (top < 0)
                        top = 0;
            }            
        }

        public void LoadProgram()
        {
            ps = new Properties.Settings();
            NextTrackMass = new List<int>();
            PrevTrackMass = new List<int>();
            MediaWindow = new MediaWindow(this);
            selectedLocalPL = new DataTable();
            selectedWebPL = new DataTable();
            playingList = new DataTable();
            groupTable = new DataTable();
            friendTable = new DataTable();
            PlayerWindow.local.DisplayMemberPath = "ArtTitle";
            PlayerWindow.local.ItemsSource = selectedLocalPL.AsDataView();
            PlayerWindow.web.DisplayMemberPath = "ArtTitle";
            PlayerWindow.web.ItemsSource = selectedWebPL.AsDataView();
            PlayerWindow.SearchBoxGroup.DisplayMemberPath = "Name";
            mediaElement = MediaWindow.VideoElement;
            mediaElement.MediaEnded += mediaElement_MediaEnded;
            mediaElement.BufferingStarted += mediaElement_BufferingStarted;
            mediaElement.BufferingEnded += mediaElement_BufferingEnded;
            mediaElement.MediaOpened += mediaElement_MediaOpened;
            ThreadWorker = new ThrearWorkClass(PlayerWindow.GetStyleItem.Style, this);
            if (ps.thisTop > Screen.PrimaryScreen.WorkingArea.Height) ps.thisTop = 0;
            if (ps.thisLeft > Screen.PrimaryScreen.WorkingArea.Width) ps.thisLeft = 0;

            PlayerWindow.Top = ps.thisTop;
            PlayerWindow.Left = ps.thisLeft;
            PlayerWindow.openedWindowHeight = ps.winHeight;
            
            PlayerWindow.Loaded += PlayerWindow_Loaded;
            LoadLocalList();
            CreateContextMenu();

            LoadHotKeys();
        }

        

        void PlayerWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (ps.SelectedPLS != "" && PlayerWindow.PLNameBox.Items.IndexOf(ps.SelectedPLS) !=-1)
            {
                PlayerWindow.PLNameBox.SelectedItem = ps.SelectedPLS;
                SelectLocalPL(ps.SelectedPLS);
            }
            if (ps.topButton)
                ChangeTopMost();
            if (ps.inTray)
                ToTray_Func();
        }

        public void CloseAplication()
        {
            ps.thisTop = PlayerWindow.Top;
            ps.thisLeft = PlayerWindow.Left;
            ps.winHeight = PlayerWindow.openedWindowHeight;
            MyNotifyIcon.Visible = false;
            if (PlayerWindow.PLNameBox.SelectedItem != null)
            {
                ps.SelectedPLS = PlayerWindow.PLNameBox.SelectedItem.ToString();
                if (playingTrackPosition > 0 && playingList.TableName.IndexOf("@vk#") == -1)
                {
                    ps.playTrackPos = playingTrackPosition;
                    ps.trackTimePos = mediaElement.Position;
                }
            }
            ps.Save();
            System.Windows.Application.Current.Shutdown();
            
        }

        public void ChangeTopMost()
        {
            if (PlayerWindow.Topmost)
            {
                PlayerWindow.LockIcon.Visibility = System.Windows.Visibility.Visible;
                PlayerWindow.UnlockIcon.Visibility = System.Windows.Visibility.Hidden;
                PlayerWindow.Topmost = false;
                ps.topButton = false;
                PlayerWindow.ShowInTaskbar = true;
            }
            else
            {
                PlayerWindow.Visibility = System.Windows.Visibility.Hidden;
                PlayerWindow.Visibility = System.Windows.Visibility.Visible;
                PlayerWindow.Topmost = true;
                ps.topButton = true;
                PlayerWindow.ShowInTaskbar = false;
            }
            ps.Save();
        }

        public bool LogIn(bool relogin)
        {
            if (access_token == null || relogin)
            {
                PlayerWindow.SearchButton.IsEnabled = false;
                LoginQuestionWindow qw = new LoginQuestionWindow(this);
                return false;
            }
            return true;
        }
        /// <param name="comand">
        /// 'p' - Play
        /// 's' - Stop
        /// 'a' - Pause
        /// </param>
        private void ChangeAllIcons(char comand)
        {
            PlayerWindow.ChangeIcons(comand);
            System.Drawing.Image playImg;
            string currentDir = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            if (comand == 'p')
            {
                playItem.Text = "Приостановить";
                try
                {
                    playImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Pause.png");
                    playItem.Image = playImg;
                    MyNotifyIcon.Icon = new System.Drawing.Icon(currentDir + @"\Themes\Icons\Play.ico");
                }
                catch { }
            }
            if (comand == 's')
            {
                if (PlayerWindow.PauseIcon.Visibility == System.Windows.Visibility.Visible)
                {
                    playItem.Text = "Воспроизвести";
                    try
                    {
                        MyNotifyIcon.Icon = new System.Drawing.Icon(currentDir + @"\Themes\Icons\Logo.ico");
                        playImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Play.png");
                        playItem.Image = playImg;
                    }
                    catch { }
                }
            }
            if (comand == 'a')
            {
                playItem.Text = "Воспроизвести";
                try
                {
                    playImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Play.png");
                    playItem.Image = playImg;
                    MyNotifyIcon.Icon = new System.Drawing.Icon(currentDir + @"\Themes\Icons\Pause.ico");
                }
                catch { }
            }
        }

        #endregion
        //----------------------------------------------------------------------------
        #region Управление VideoElement

        private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            try
            {
                if (selectedWebPL.TableName == playingList.TableName)
                    PlayerWindow.timelineSlider.Maximum = Convert.ToInt32(playingList.Rows[playingTrackPosition].ItemArray[6]);
                else
                    PlayerWindow.timelineSlider.Maximum = (int)Math.Round(mediaElement.NaturalDuration.TimeSpan.TotalSeconds, MidpointRounding.AwayFromZero);
                SetArtTitle(playingList.Rows[playingTrackPosition].ItemArray[3].ToString());
                StartTimer();
            }
            catch
            {

            }
        }

        public void ChangeTime(double value)
        {
            int minutes = (int)Math.Round(value) / 60;
            int seconds = (int)Math.Round(value) % 60;
            string min;
            string sec;
            if (minutes < 10) min = "0" + minutes.ToString();
            else min = minutes.ToString();
            if (seconds < 10) sec = "0" + seconds.ToString();
            else sec = seconds.ToString();
            PlayerWindow.Time.Content = min + ":" + sec;
        }

        public void ChangeSliderValue(double value)
        {
            PlayerWindow.timelineSlider.Value = value;
            mediaElement.Position = TimeSpan.FromSeconds(value);
        }

        int emptyFiles = 0;
        private void Play(int position)
        {
            if (playingList.Rows.Count != 0)
            {
                DataRow row;
                playingTrackPosition = position;
                Stop();
                row = playingList.Rows[position];
                string source = row.ItemArray[2].ToString();
                Uri url = new Uri(source);;
                if (PlayerWindow.PLNameBox.Items.Count !=0)
                    if (selectedLocalPL.TableName == playingList.TableName)
                    {
                        if (File.Exists(source) || source.IndexOf("http://") != -1)
                            url = new Uri(source);
                        else
                        {
                            emptyFiles++;
                            if (emptyFiles == playingList.Rows.Count)
                            {
                                emptyFiles = 0;
                                Stop();
                                return;
                            }
                            NextTrack();
                        }
                        PlayerWindow.local.SelectedIndex = playingTrackPosition;
                        PlayerWindow.local.ScrollIntoView(PlayerWindow.local.SelectedItems[0]);
                        PlayerWindow.local.UpdateLayout();
                    }
                if (selectedWebPL.TableName == playingList.TableName)
                {
                    PlayerWindow.web.SelectedIndex = playingTrackPosition;
                    PlayerWindow.web.ScrollIntoView(PlayerWindow.web.SelectedItems[0]);
                    PlayerWindow.web.UpdateLayout();
                }
                mediaElement.Source = url;
                ChangeAllIcons('p');
                mediaIsPaused = false;
                mediaIsStop = false;
                mediaElement.Play();
            }
        }

        public void Play(DataRowView track)
        {
            if (track != null)
            {
                int pos = 0;
                if (track.DataView.Table.Columns[1].ColumnName == "Oid")
                {
                    pos = PlayerWindow.web.Items.IndexOf(track);
                    if (playingList.Rows.Count != selectedWebPL.Rows.Count || playingList.TableName != selectedWebPL.TableName)
                        playingList = selectedWebPL.Copy();
                    Play(pos);
                }
                else
                {
                    pos = PlayerWindow.local.Items.IndexOf(track);
                    if (pos == -1)
                        pos = selectedLocalPL.Rows.IndexOf(track.Row);
                    if (playingList.Rows.Count != selectedLocalPL.Rows.Count || playingList.TableName != selectedLocalPL.TableName)
                        playingList = selectedLocalPL.Copy();
                    Play(pos);
                }
                NextTrackMass.Clear();
                RefreshNextMass();
                PrevTrackMass.Clear();
                playingShufflePosition = -1;
                NextTrackMass.Remove(pos);
                PrevTrackMass.Add(pos);
            }
        }

        private void RefreshNextMass()
        {
            for (int i = NextTrackMass.Count; i < playingList.Rows.Count; i++)
                NextTrackMass.Add(i);
        }

        public void Stop()
        {
            StopTimer();
            PlayerWindow.timelineSlider.Value = 0;
            mediaElement.Stop();
            mediaElement.Source = null;
            mediaIsPaused = true;
            mediaIsStop = true;
            ChangeAllIcons('s');
        }

        public void PlayPause()
        {
            if (mediaElement.Source != null)
            {
                if (mediaIsPaused)
                {
                    StartTimer();
                    mediaElement.Play();
                    ChangeAllIcons('p');
                    mediaIsPaused = false;
                    mediaIsStop = false;
                }
                else
                {
                    StopTimer();
                    mediaElement.Pause();
                    ChangeAllIcons('a');
                    mediaIsPaused = true;
                }
            }
            else
            {
                if (playingList != null)
                    if (playingTrackPosition <= playingList.Rows.Count && playingList.Rows.Count != 0)
                    {
                        Play(playingTrackPosition);
                        ChangeAllIcons('p');
                        return;
                    }
                if (PlayerWindow.web.SelectedValue != null)
                {
                    Play((DataRowView)PlayerWindow.web.SelectedValue);
                    return;
                }
                if (PlayerWindow.web.SelectedValue != null)
                {
                    Play((DataRowView)PlayerWindow.web.SelectedValue);
                    return;
                }
                if (selectedLocalPL != null)
                    if (PlayerWindow.local.Items.Count != 0)
                    {
                        Play((DataRowView)PlayerWindow.local.Items[0]);
                        ChangeAllIcons('p');
                    }
            }
        }

        private void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            if (repeatPlay)
            {
                mediaElement.Stop();
                mediaElement.Source = null;
                Play(playingTrackPosition);
            }
            else
                NextTrack();
        }

        private void mediaElement_BufferingStarted(object sender, RoutedEventArgs e)
        {
            PlayerWindow.ArtistTitle.Content = "Буфферизация...";
            StopTimer();
        }

        void mediaElement_BufferingEnded(object sender, RoutedEventArgs e)
        {
            SetArtTitle(playingList.Rows[playingTrackPosition].ItemArray[3].ToString());
            StartTimer();
        }

        private void SetArtTitle(string artTitle)
        {
            PlayerWindow.ArtistTitle.Content = artTitle;
            if (playingList.TableName.IndexOf("@vk#") > -1)
                PlayerWindow.Title = artTitle;
            else
                PlayerWindow.Title = artTitle;
        }

        public void NextTrack()
        {
            if (playingList.Rows.Count != 0)
            {
                int position = 0;
                //
                //Случайным образом
                if (shufflePlay)
                {
                    if (playingShufflePosition <= -1)
                    {
                        if (NextTrackMass.Count == 0)
                        {
                            PrevTrackMass.Clear();
                            RefreshNextMass();
                        }
                        int rand_pos = Random(NextTrackMass.Count);
                        position = NextTrackMass[rand_pos];
                        NextTrackMass.Remove(position);
                        PrevTrackMass.Add(position);
                    }
                    else
                    {
                        playingShufflePosition++;
                        position = PrevTrackMass[PrevTrackMass.Count + playingShufflePosition];
                    }
                }
                //
                //По порядку
                else
                {
                    position = playingTrackPosition + 1;
                    if (position > playingList.Rows.Count - 1)
                        position = 0;
                }
                    Play(position);

            }
        }

        public void PrevTrack()
        {
            int position = 0;
            //
            //Случайым образом
            if (shufflePlay)
            {

                if (Math.Abs(playingShufflePosition) >= PrevTrackMass.Count)
                {
                    Stop();
                    return;
                }
                else
                {
                    playingShufflePosition--;
                    position = PrevTrackMass[PrevTrackMass.Count + playingShufflePosition];
                }
            }
            //
            //По порядку
            else
            {
                if (playingTrackPosition > 0)
                    position = playingTrackPosition - 1;
                else
                {
                    Stop();
                    return;
                }
            }
            Play(position);
        }

        private int Random(int max)
        {
            RNGCryptoServiceProvider random;
            random = new RNGCryptoServiceProvider();
            byte[] buffer = new byte[4];
            random.GetBytes(buffer);
            int number = BitConverter.ToInt32(buffer, 0);
            number = new Random(number).Next(0, max);
            return number;
        }

        #endregion 
        //----------------------------------------------------------------------------
        #region Уплавление плейлистами

        public void SelectLocalPL(string name)
        {
            if (ThreadWorker.tableDec.ContainsKey(name))
            {
                selectedLocalPL = ThreadWorker.tableDec[name];
            }
            else
            {
                selectedLocalPL = new DataTable();               
                selectedLocalPL.TableName = name;
                FillLocalTable(selectedLocalPL);
            }
            PlayerWindow.local.ItemsSource = selectedLocalPL.AsDataView();
        }

        public void LoadLocalList()
        {
            OleDbConnection oleCon = new OleDbConnection(ps.PLSConnectionString);
            oleCon.Open();
            DataTable tabl = oleCon.GetSchema("Tables");
            oleCon.Close();
            foreach (DataRow row in tabl.Rows)
                if (row.ItemArray[3].ToString() != "ACCESS TABLE" && row.ItemArray[3].ToString() != "SYSTEM TABLE")
                    if (row.ItemArray[3].ToString() == "TABLE")
                        PlayerWindow.PLNameBox.Items.Add(row.ItemArray[2].ToString());

        }

        private void UpdateLocalTable (DataTable table)
        {
            OleDbConnection oleCon = new OleDbConnection(ps.PLSConnectionString);
            OleDbDataAdapter adapter = new OleDbDataAdapter();

            string[] columnsName = new string[5] { "Path", "ArtTitle", "Artist", "Album", "Genres" };
            OleDbParameter[] paramArray = new OleDbParameter[7];
            OleDbParameter[] newArr = new OleDbParameter[7];
            OleDbParameter par;
            for (int i = 2; i < columnsName.Length+2; i++)
            {
                par = new OleDbParameter(columnsName[i-2], OleDbType.VarChar, 200, columnsName[i-2]);
                paramArray[i] = par;
                par = new OleDbParameter(columnsName[i-2], OleDbType.VarChar, 200, columnsName[i-2]);
                newArr[i] = par;
            }
            par = new OleDbParameter("Year", OleDbType.SmallInt, 4, "Year");
            paramArray[1] = par;
            par = new OleDbParameter("Year", OleDbType.SmallInt, 4, "Year");
            newArr[1] = par;

            par = new OleDbParameter("ID", OleDbType.Integer, 0, "ID");
            paramArray[0] = par;
            par = new OleDbParameter("ID", OleDbType.Integer, 0, "ID");
            newArr[0] = par;

            OleDbCommand comand = new OleDbCommand("SELECT * FROM [" + table.TableName + "]", oleCon);
            adapter.SelectCommand = comand;

            comand = new OleDbCommand(String.Format("UPDATE [" + table.TableName + "] SET [ID] = ?, [Year] = ?, [{0}] = ?, [{1}] = ?, [{2}] = ?, [{3}] = ?, [{4}] = ? WHERE [ID] = ?", columnsName), oleCon);
            comand.Parameters.AddRange(paramArray);
            OleDbParameter param = new OleDbParameter("ID", OleDbType.Integer, 0, "ID");
            param.SourceVersion = DataRowVersion.Original;
            adapter.UpdateCommand = comand;

            comand = new OleDbCommand(String.Format("INSERT INTO [" + table.TableName + "] ([ID], [Year], [{0}], [{1}], [{2}], [{3}], [{4}]) VALUES (?, ?, ?, ?, ?, ?, ?)", columnsName), oleCon);
            comand.Parameters.AddRange(newArr);
            adapter.InsertCommand = comand;

            comand = new OleDbCommand("DELETE * FROM [" + table.TableName + "] WHERE ID = ?", oleCon);
            comand.Parameters.Add("ID", OleDbType.Integer, 0, "ID").Value = 0;
            adapter.DeleteCommand = comand;
            try
            {
                adapter.Update(table);
            }
            catch { }
        }

        private void FillLocalTable(DataTable table)
        {
            OleDbConnection oleCon = new OleDbConnection(ps.PLSConnectionString);
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + table.TableName + "]", oleCon);
            adapter.Fill(table);
        }

        public void UpdateTable(DataTable table)
        {
            PlayerWindow.doAnimation = false;
            if (table.TableName.IndexOf("#") == -1)
                UpdateLocalTable(table);
            else
                if (playingList.TableName == selectedWebPL.TableName)
                        playingList = selectedWebPL.Copy();
            RefreshNextMass();
        }

        /// <param name="how">"ASC", "DESC"</param>
        public DataView SortTable(DataTable table, string param, string how)
        {
            DataView view = table.AsDataView();
            view.Sort = param + " " + how;
            return view;
        }

        public void AddTrackToPL(string[] pathMass)
        {
            ThreadWorker.AddLocalTrack(selectedLocalPL, pathMass);
        }

        public void DeletePL(string name)
        {
            if (ThreadWorker.tableDec.ContainsKey(name))
                ThreadWorker.tableDec.Remove(name);
            OleDbConnection oleCon = new OleDbConnection(ps.PLSConnectionString);
            oleCon.Open();
            OleDbCommand comand = new OleDbCommand("DROP TABLE [" + name + "]", oleCon);
            comand.ExecuteNonQuery();
            oleCon.Close();
            selectedLocalPL.Clear();
        }

        public void AddNewPL(string name)
        {
            OleDbCommand com = new OleDbCommand("CREATE TABLE [" + name + "] ([ID] INT PRIMARY KEY, [Year] SHORT, [Path] VARCHAR, [ArtTitle] VARCHAR, [Artist] VARCHAR, [Album] VARCHAR, [Genres] VARCHAR)");
            com.Connection = new OleDbConnection(ps.PLSConnectionString);
            com.Connection.Open();
            com.ExecuteNonQuery();
            com.Connection.Close();
        }

        public void CreateContextMenu()
        {
            System.Windows.Controls.ContextMenu Lmenu = new System.Windows.Controls.ContextMenu();
            System.Windows.Controls.ContextMenu Wmenu = new System.Windows.Controls.ContextMenu();

            Aitem = new System.Windows.Controls.MenuItem();
            Aitem.IsEnabled = false;
            Lmenu.Items.Add(Aitem);

            Titem = new System.Windows.Controls.MenuItem();
            Titem.IsEnabled = false;
            Lmenu.Items.Add(Titem);

            ALitem = new System.Windows.Controls.MenuItem();
            ALitem.IsEnabled = false;
            Lmenu.Items.Add(ALitem);

            Gitem = new System.Windows.Controls.MenuItem();
            Gitem.IsEnabled = false;
            Lmenu.Items.Add(Gitem);

            System.Windows.Controls.MenuItem copyItem = new System.Windows.Controls.MenuItem();
            copyItem.Name = "local";
            copyItem.Header = "Копировать название";
            copyItem.Click += new RoutedEventHandler(CopyTitleToBuffer);
            Lmenu.Items.Add(copyItem);

            PlayerWindow.local.ContextMenu = Lmenu;
        }

        private void AddSongToMyAudio(object sender, RoutedEventArgs e)
        {
            var r = PlayerWindow.web.SelectedItem as DataRowView;
            string doc = GetRequest("audio.add?aid=" + r[0] + "&oid=" + r[1]);
            if (doc.IndexOf("error") > -1)
               System.Windows.MessageBox.Show("Ошибка при добавлении трека");
        }

        private void DelSongOfMyAudio(object sender, RoutedEventArgs e)
        {
            var r = PlayerWindow.web.SelectedItem as DataRowView;
            string doc = GetRequest("audio.delete?aid=" + r[0] + "&oid=" + r[1]);
            if (doc.IndexOf("error") > -1)
                System.Windows.MessageBox.Show("Ошибка при удалении трека");
            else
                selectedWebPL.Rows.Remove(r.Row);
        }

        private void GetSongOfMyAudio(object sender, RoutedEventArgs e)
        {
            var r = PlayerWindow.web.SelectedItem as DataRowView;
            DialogWindow.DownloadWindow DW = new DialogWindow.DownloadWindow(r[2].ToString(), r[3] + ".mp3");
        }

        private void CopyTitleToBuffer(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Controls.MenuItem it = sender as System.Windows.Controls.MenuItem;
                if (it.Name == "web")
                    System.Windows.Clipboard.SetText(((DataRowView)PlayerWindow.web.SelectedItem).Row[3].ToString());
                else
                    System.Windows.Clipboard.SetText(((DataRowView)PlayerWindow.local.SelectedItem).Row[3].ToString());
            }
            catch
            {

            }
        }

        public void ShowItemContexMenu(DataRowView row)
        {
            if (row != null)
            {
                Aitem.Header = "Артист: " + row[4];
                Titem.Header = "Название: " + row[3].ToString().Split('-')[1];
                ALitem.Header = "Альбом: " + row[5];
                Gitem.Header = "Жанр: " + row[6];
            }
        }
        #endregion
        //----------------------------------------------------------------------------
        #region Таймеры

        
        private void sliderTimer_Tick(object sender, object e)
        {
            if (!sliderpressed)
            {
                PlayerWindow.timelineSlider.Value++;
            }
        }
        /*
        public string originalTitle;
        bool back = false;
        private void stringTimer_Tick(object sender, object e)
        {
            if (back)
            {
                int index = originalTitle.IndexOf(PlayerWindow.ArtistTitle.Content.ToString()) - 1;
                PlayerWindow.ArtistTitle.Content = PlayerWindow.ArtistTitle.Content.ToString().Insert(0, originalTitle[index].ToString());
                if (PlayerWindow.ArtistTitle.Content.ToString() == originalTitle)
                {
                    stringTimer.Stop();
                    stringTimer.Tick -= stringTimer_Tick;
                    back = false;
                }
            }
            else
            {
                PlayerWindow.ArtistTitle.Content = PlayerWindow.ArtistTitle.Content.ToString().Remove(0, 1);
                if (PlayerWindow.ArtistTitle.Content.ToString().Length * 6.2 <= PlayerWindow.TopBorder.Width)
                    back = true;
            }
            
        }

        private void timerTimer_Tick(object sender, object e)
        {
            stringTimer.Tick += stringTimer_Tick;
            stringTimer.Start();
        }
        */

        private void StartTimer()
        {
            //sliderTimer.Tick += sliderTimer_Tick;
            sliderTimer.Start();
            if (PlayerWindow.ArtistTitle.Content.ToString().Length * 6.2 >= PlayerWindow.TopBorder.Width && PlayerWindow.IsVisible)
            {
                int time = Convert.ToInt32((PlayerWindow.ArtistTitle.Content.ToString().Length * 6.2 - PlayerWindow.TopBorder.Width)/5);
                //originalTitle = PlayerWindow.ArtistTitle.Content.ToString();
                timerTimer.Interval = time + 8000;
                //timerTimer.Tick+=timerTimer_Tick;
                //back = false;
                timerTimer.Start();
            }
        }

        private void StopTimer()
        {
            sliderTimer.Stop();
            //sliderTimer.Tick -= sliderTimer_Tick;
        }


        #endregion
        //----------------------------------------------------------------------------
        #region Иконка в трее
        System.Windows.Forms.ToolStripMenuItem playItem;
        System.Windows.Forms.ContextMenuStrip menu;
        private void LoadNotiIcon()
        {
            string currentDir = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            MyNotifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
            MyNotifyIcon.MouseDoubleClick += MyNotifyIcon_MouseDoubleClick;
            menu = new System.Windows.Forms.ContextMenuStrip();
            //
            System.Windows.Forms.ToolStripMenuItem nextItem = new System.Windows.Forms.ToolStripMenuItem("Следующий трек");
            nextItem.Click += new EventHandler(NotiNext);
            menu.Items.Add(nextItem);
            //
            System.Windows.Forms.ToolStripMenuItem prevItem = new System.Windows.Forms.ToolStripMenuItem("Предведущий трек");
            prevItem.Click += new EventHandler(NotiPrev);
            menu.Items.Add(prevItem);
            //
            playItem = new System.Windows.Forms.ToolStripMenuItem("Воспроизвести");
            playItem.Click += new EventHandler(NotiPlay);
            menu.Items.Add(playItem);
            //
            System.Windows.Forms.ToolStripMenuItem exitItem = new System.Windows.Forms.ToolStripMenuItem("Выход");
            exitItem.Click += new EventHandler(NotiClose);
            menu.Items.Add(exitItem);
            //
            try
            {
                System.Drawing.Image nextImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Next.png");
                nextItem.Image = nextImg;
                System.Drawing.Image prevImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Prev.png");
                prevItem.Image = prevImg;
                System.Drawing.Image playImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Play.png");
                playItem.Image = playImg;
                System.Drawing.Image exitImg = System.Drawing.Image.FromFile(currentDir + @"\Themes\Images\Close.png");
                exitItem.Image = exitImg;
            }
            catch { }
            //
            MyNotifyIcon.ContextMenuStrip = menu;
        }

        private void NotiClose(object sender, EventArgs e)
        {
            CloseAplication();
        }

        private void NotiNext(object sender, EventArgs e)
        {
            NextTrack();
        }

        private void NotiPrev(object sender, EventArgs e)
        {
            PrevTrack();
        }

        private void NotiPlay(object sender, EventArgs e)
        {
            PlayPause();
        }

        public void ToTray_Func()
        {
            if (ps.inTray)
            {
                timerTimer.Start();
                MyNotifyIcon.Visible = false;
                ps.inTray = false;
                ps.Save();
                PlayerWindow.ShowInTaskbar = true;
                PlayerWindow.WindowState = WindowState.Normal;
                PlayerWindow.Show();
                PlayerWindow.Activate();
            }
            else
            {
                timerTimer.Stop();
                HotKey.HideFromAltTab(new WindowInteropHelper(PlayerWindow).Handle);
                PlayerWindow.WindowState = System.Windows.WindowState.Minimized;
                PlayerWindow.ShowInTaskbar = false;
                MyNotifyIcon.Visible = true;
                ps.inTray = true;
                ps.Save();
            }
        }

        void MyNotifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            ToTray_Func();
        }
        #endregion
        //----------------------------------------------------------------------------
        #region Управление Веб плейлистами

        public void SetAuData(string id, string token)
        {
            user_id = id;
            access_token = token;
            Process[] procList = Process.GetProcesses();
            DisableIE();
            SelectWebTable(PlayerWindow.selectedTab,PlayerWindow.CheckTabName(),"",false);
            EnableVkButton();
        }

        public void EnableVkButton()
        {
            PlayerWindow.OpenCloseTitle('w');
            PlayerWindow.SearchButton.IsEnabled = true;
        }

        public bool CreateGroupsList()
        {
            if (groupTable.Rows.Count == 0)
            {
                groupTable.Columns.Clear();
                groupTable.Columns.Add("Id", typeof(Int32));
                groupTable.Columns.Add("Count", typeof(Int32));
                groupTable.Columns.Add("Name", typeof(String));
                groupTable.TableName = "Groups";
                DataColumn[] keys = new DataColumn[1];
                keys[0] = groupTable.Columns[0];
                groupTable.PrimaryKey = keys;
                ThreadWorker.GetUserGroups(user_id, groupTable);
                DataView view = groupTable.AsDataView();
                view.Sort = "Count DESC";
                PlayerWindow.SearchBoxGroup.ItemsSource = view;
                return true;
            }
            else
            {
                DataView view = groupTable.AsDataView();
                view.Sort = "Count DESC";
                PlayerWindow.SearchBoxGroup.ItemsSource = view;
                return false;
            }
        }

        public bool CreateFriendList()
        {
            if (friendTable.Rows.Count == 0)
            {
                friendTable.Columns.Clear();
                friendTable.Columns.Add("Id", typeof(Int32));
                friendTable.Columns.Add("Name", typeof(String));
                friendTable.TableName = "Friends";
                ThreadWorker.GetUserFriends(user_id, friendTable);
                PlayerWindow.SearchBoxGroup.ItemsSource = friendTable.AsDataView();
                return true;
            }
            else
            {
                PlayerWindow.SearchBoxGroup.ItemsSource = friendTable.AsDataView();
                return false;
            }
        }

        private void CreateWebContextMenu(int code)
        {
            if (selectedWebPL.TableName != "")
            {
                char oldCode = selectedWebPL.TableName.Split('#')[0][0];
                if ((oldCode == '0' && code == 0) || (oldCode != '0' && code != 0))
                    return;
            }
            System.Windows.Controls.ContextMenu Wmenu = new System.Windows.Controls.ContextMenu();

            WAitem = new System.Windows.Controls.MenuItem();
            WAitem.IsEnabled = false;
            Wmenu.Items.Add(WAitem);

            WTitem = new System.Windows.Controls.MenuItem();
            WTitem.IsEnabled = false;
            Wmenu.Items.Add(WTitem);

            WGitem = new System.Windows.Controls.MenuItem();
            WGitem.IsEnabled = false;
            Wmenu.Items.Add(WGitem);

            string currentDir = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            if (code == 0)
            {
                System.Windows.Controls.MenuItem delItem = new System.Windows.Controls.MenuItem();
                delItem.Header = "Удалить из моих аудиозаписей";
                try
                {
                    System.Windows.Controls.Image delImg = new System.Windows.Controls.Image();
                    delImg.Source = new BitmapImage(new Uri(currentDir + @"\Themes\Images\Minus.png"));
                    delItem.Icon = delImg;
                }
                catch { }
                delItem.Click += new RoutedEventHandler(DelSongOfMyAudio);
                Wmenu.Items.Add(delItem);
            }
            else
            {
                System.Windows.Controls.MenuItem addItem = new System.Windows.Controls.MenuItem();
                addItem.Header = "Добавить в мои аудиозаписи";
                try
                {
                    System.Windows.Controls.Image addImg = new System.Windows.Controls.Image();
                    addImg.Source = new BitmapImage(new Uri(currentDir + @"\Themes\Images\Plus.png"));
                    addItem.Icon = addImg;
                }
                catch { }
                addItem.Click += new RoutedEventHandler(AddSongToMyAudio);
                Wmenu.Items.Add(addItem);
            }
            //
            System.Windows.Controls.MenuItem getItem = new System.Windows.Controls.MenuItem();
            getItem.Header = "Скачать";
            try
            {
                System.Windows.Controls.Image getImg = new System.Windows.Controls.Image();
                getImg.Source = new BitmapImage(new Uri(currentDir + @"\Themes\Images\Down.png"));
                getItem.Icon = getImg;
            }
            catch { }
            getItem.Click += new RoutedEventHandler(GetSongOfMyAudio);
            Wmenu.Items.Add(getItem);
            //
            System.Windows.Controls.MenuItem copyItem = new System.Windows.Controls.MenuItem();
            copyItem.Header = "Копировать название";
            copyItem.Name = "web";
            copyItem.Click += new RoutedEventHandler(CopyTitleToBuffer);
            Wmenu.Items.Add(copyItem);
            PlayerWindow.web.ContextMenu = Wmenu;
        }

        public void ShowWebContextMenu(DataRowView row)
        {
            if (row != null)
            {
                WAitem.Header = "Артист: " + row[4];
                WTitem.Header = "Название: " + row[3].ToString().Split('-')[1];
                WGitem.Header = "Жанр: " + row[5];
            }
        }

        public DataTable FillGroupCountList()
        {
            DataTable tab = new DataTable();
            OleDbConnection con = new OleDbConnection(ps.VKLConnection);
            OleDbDataAdapter adapt = new OleDbDataAdapter("SELECT * FROM [Groups]", con);
            try
            {
                con.Open();
                adapt.Fill(tab);
                return tab;
            }
            catch (Exception ex)
            { System.Windows.MessageBox.Show(ex.Message); }
            finally
            { con.Close(); }
            return null;
        }

        private void IncrementSelectCount(DataRow row)
        {
            int count = Convert.ToInt32(row[1]);
            count++;
            OleDbConnection oleCon = new OleDbConnection(ps.VKLConnection);
            OleDbCommand comand = new OleDbCommand("UPDATE [" + row.Table.TableName + "] SET [Count] = ? WHERE [Id] = ?", oleCon);
            comand.Parameters.Add("Count", OleDbType.Integer, 0, "Count").Value = count;
            comand.Parameters.Add("Id", OleDbType.Integer, 12, "Id").Value = row[0];
            try
            {
                oleCon.Open();
                comand.ExecuteNonQuery();
            }
            catch (Exception ex)
            { System.Windows.MessageBox.Show(ex.Message); }
            finally
            { oleCon.Close(); }
        }

        public void InsertNewVkGroup(DataRow row)
        {
            OleDbConnection oleCon = new OleDbConnection(ps.VKLConnection);
            OleDbCommand comand = new OleDbCommand("INSERT INTO [" + row.Table.TableName + "] ([Id], [Count]) VALUES (@Id, @Count)", oleCon);
            comand.Parameters.Add("@Id", OleDbType.Integer, 12, "Id").Value = row[0];
            comand.Parameters.Add("@Count", OleDbType.Integer, 0, "Count").Value = 0;
            try
            {
                oleCon.Open();
                comand.ExecuteNonQuery();
            }
            catch (Exception ex)
            { System.Windows.MessageBox.Show(ex.Message); }
            finally
            { oleCon.Close(); }
        }

        private void DisableIE()
        {
            Thread bWeit = new Thread(new ThreadStart(KillIE));
            bWeit.Start();
        }

        private static void KillIE()
        {
            for (int t=0;t<30;t++)
            {
                if (Process.GetProcessesByName("iexplore").Length > 0)
                {
                    Process[] IeMass = Process.GetProcessesByName("iexplore");
                    for (int i = 0; i < IeMass.Length; i++)
                    {
                        if (IeMass[i].MainWindowTitle == "OAuth Blank - Windows Internet Explorer")
                        {
                            IeMass[i].CloseMainWindow();
                            return;
                        }
                    }
                }
                Thread.Sleep(1500);
            }
        }

        /// <param name="code">0 - UserAudio; 1 - UserWall; 2 - GroupAudio; 3 - GroupWall; 4 - FriendAudio; 
        /// 5 - FriendWall; 6 - SearchAudio; 9 - Newsfeed</param>
        /// <param name="id">"user" - current user id;"group" - current group; "friend" - current friend; searchString - if seaarch audio</param>
        public void SelectWebTable(int code, string id, string albumId, bool isRefrash)
        {
            if (code == 20)
                return;
            if (id == "user")
                id = user_id;
            if (id == "group")
                id = group_id;
            if (id == "friend")
                id = friend_id;
            if (id == null)
                return;
            if (playingList.TableName == code + "#" + id + "#" + albumId && isRefrash == false)
            {
                selectedWebPL = playingList.Copy();
                PlayerWindow.web.ItemsSource = selectedWebPL.AsDataView();
                PlayerWindow.doAnimation = false;
            }
            else
            {
                CreateWebContextMenu(code);
                ClearWebTable();
                CreateWebTable(code);
                selectedWebPL.TableName = code.ToString() + "#" + id + "#" + albumId;
                ThreadWorker.AddWebTrack(selectedWebPL);
                PlayerWindow.web.ItemsSource = selectedWebPL.AsDataView();
                PlayerWindow.doAnimation = true;
                PlayerWindow.BeginRotateAnimation();
            }
        }

        public void ClearWebTable()
        {
            ThreadWorker.CancelWebAddition();
            selectedWebPL.Clear();
            selectedWebPL = new DataTable();
            PlayerWindow.doAnimation = false;
        }

        public void StopUpdate()
        {
            ThreadWorker.CancelWebAddition();
            PlayerWindow.doAnimation = false;
        }

        public void SelectBoxItem(object row, int code)
        {
            DataRowView Row = (DataRowView)row;
            string name = Row.Row.Table.TableName;
            string id = ""; string albumId = "";
            switch (name)
            {
                case "Groups":
                    IncrementSelectCount(Row.Row);
                    Row[1] = Convert.ToInt32(Row[1]) + 1;
                    group_id = Row[0].ToString();
                    id = group_id;
                    break;
                case "Friends":
                    friend_id = Row[0].ToString();
                    id = friend_id;
                    break;
                case "UserAlbum":
                    id = user_id;
                    albumId = Row[0].ToString();
                    break;
                case "GroupAlbum":
                    id = group_id;
                    albumId = Row[0].ToString();
                    break;
                case "FriendAlbum":
                    id = friend_id;
                    albumId = Row[0].ToString();
                    break;
            }
            SelectWebTable(code, id, albumId, false);
        }

        private void CreateWebTable(int code)
        {
            selectedWebPL.Columns.Add("Aid", typeof(Int32));
            selectedWebPL.Columns.Add("Oid", typeof(Int32));
            selectedWebPL.Columns.Add("Url", typeof(String));
            selectedWebPL.Columns.Add("ArtTitle", typeof(String));
            selectedWebPL.Columns.Add("Artist", typeof(String));
            selectedWebPL.Columns.Add("Genres", typeof(String));
            selectedWebPL.Columns.Add("Duration", typeof(Int32));
            if (code % 2 == 1) //стена
                selectedWebPL.Columns.Add("Pid", typeof(Int32));
        }

        public string GetRequest(string Data)
        {
            string urlMetod = "https://api.vk.com/method/";
            TimeSpan stopTimer = DateTime.Now - startTimer;
            int sleepTime = Convert.ToInt32(stopTimer.TotalMilliseconds);
            if (sleepTime > 330 || sleepTime < 0)
                sleepTime = 0;
            else
                sleepTime = 330 - sleepTime;
            System.Threading.Thread.Sleep(sleepTime);
            System.Net.WebRequest req = System.Net.WebRequest.Create(urlMetod + Data + "&access_token=" + access_token);
            startTimer = DateTime.Now;
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.Stream stream = resp.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            try
            {
                string Out = sr.ReadToEnd();
                sr.Close();
                return Out;
            }
            catch (System.Net.WebException e)
            {
                System.Windows.MessageBox.Show(e.Message);
            }
            return null;
        }
        #endregion
        //--------------------------------------------------------------------------
    }
}

